from lxml import etree
import re
from typing import AnyStr,TypedDict, List, Dict
from datetime import datetime, timedelta

class Danmu(TypedDict):
    danmu_time: float
    danmu_content: AnyStr

class Guard(TypedDict):
    guard_time: float
    guard_level: int
    guard_count: int

class Gift(TypedDict):
    gift_time: float
    gift_name: int
    gift_count: int

class Superchat(TypedDict):
    sc_time: float
    sc_price: float
    sc_content: AnyStr

class LiveRoomDataProcessor:
    def __init__(self, xml_path):
        self.xml_path = xml_path
        self.broadcast_title: AnyStr = ''
        self.broadcast_start_time: AnyStr = ''
        self.danmus: List[Danmu] = []  # 存储弹幕信息
        self.gifts: List[Gift] = []   # 存储礼物信息
        self.superchats : List[Superchat] = []  # 存储醒目留言信息
        self.guards : List[Guard] = []
        self._load_data()

    def _load_data(self):
        context = etree.iterparse(self.xml_path, events=("end",), remove_blank_text=True,
                                  tag=("BililiveRecorderRecordInfo", "d", "guard", "sc", "gift"))
        for event, elem in context:
            name = elem.tag
            if name == 'BililiveRecorderRecordInfo':
                broadcast_title = elem.get("title")
                broadcast_start_time = elem.get("start_time")
                self.broadcast_title = broadcast_title
                self.broadcast_start_time = broadcast_start_time
            elif name == 'd':
                danmu_time = elem.get("p").split(',')[0]
                danmu_content = elem.text
                danmu: Danmu = {
                    danmu_time: self.process_finalTime(self.broadcast_start_time, float(danmu_time)),
                    danmu_content: danmu_content
                }
                self.danmus.append(danmu)
            elif name == 'guard':
                guard_time = elem.get("ts")
                guard_level = elem.get("level")
                guard_count = elem.get("count")
            elif name == 'sc':
                sc_time = elem.get("ts")
                sc_price = elem.get("price")
                sc_content = elem.text
            elif name == 'gift':
                gift_time = elem.get("ts")
                gift_name = elem.get("giftname")
                gift_count = elem.get("giftcount")
            elem.clear()  # 释放当前元素内存
            while elem.getprevious() is not None:  # 清理已处理的兄弟节点
                del elem.getparent()[0]

    def process_finalTime(self, original_time_str: AnyStr, add_seconds: float):
        """
        正则方案实现时间处理并插入数据库
        :param original_time_str: 原始时间字符串（示例：2025-03-14T10:15:15.9598306+08:00）
        :param add_seconds: 需添加的秒数（示例：132.833）
        """
        # 使用正则提取日期和时间部分（精确匹配到秒）
        pattern = r"(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})"
        match = re.search(pattern, original_time_str)

        if not match:
            raise ValueError("无效的时间格式")

        # 组合成可解析的字符串
        datetime_str = f"{match.group(1)} {match.group(2)}"

        # 转换为无时区datetime对象（假设原始时间已是北京时间）
        base_time = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")

        # 秒数取整处理（直接舍去小数）
        add_seconds_int = int(add_seconds)

        # 计算新时间
        new_time = base_time + timedelta(seconds=add_seconds_int)

        # 格式化为数据库字符串
        db_time_str = new_time.strftime("%Y-%m-%d %H:%M:%S")

        return db_time_str

if __name__ =='__main__':
    xml_dir = r'C:\Users\HP\Videos\lubojiTest\27882637-罗塞菈Rosella\录制-27882637-20250314-101515-801-【港V】粤语甜妹晨起播播.xml'
    live_room_data_processor = LiveRoomDataProcessor(xml_dir)

